//
//  VerifyCodeViewController.swift
//  Nahuo
//
//  Created by zang qilong on 2017/5/8.
//  Copyright © 2017年 zang qilong. All rights reserved.
//

import UIKit
import URLNavigator
import MBProgressHUD
import SwiftyJSON
import YYModel

final class VerifyCodeViewController: UIViewController {

    @IBOutlet weak var firstCodeTextField: UITextField!
    @IBOutlet weak var secondCodeTextField: UITextField!
    @IBOutlet weak var thirdCodeTextField: UITextField!
    @IBOutlet weak var fourthCodeTextField: UITextField!
    
    @IBOutlet weak var phoneNumberLabel: UILabel!
    @IBOutlet weak var secondsLabel: UILabel!
    @IBOutlet weak var tipsLabel: UILabel!
    @IBOutlet weak var resendButton: UIButton!
    
    var phoneNum:String?
    var fetchedCode:String?
    var codeTimer:Timer!
    var codeSeconds = 60
    
    override func viewDidLoad() {
        super.viewDidLoad()
        firstCodeTextField.tag = 10001;
        firstCodeTextField.delegate = self;
        secondCodeTextField.tag = 10002;
        secondCodeTextField.delegate = self;
        thirdCodeTextField.tag = 10003;
        thirdCodeTextField.delegate = self;
        fourthCodeTextField.tag = 10004;
        fourthCodeTextField.delegate = self;
        
        firstCodeTextField.layer.borderColor = UIColor.codeTextFieldBorderColor().cgColor
        secondCodeTextField.layer.borderColor = UIColor.codeTextFieldBorderColor().cgColor
        thirdCodeTextField.layer.borderColor = UIColor.codeTextFieldBorderColor().cgColor
        fourthCodeTextField.layer.borderColor = UIColor.codeTextFieldBorderColor().cgColor
        
        firstCodeTextField.layer.borderWidth = 2.0
        secondCodeTextField.layer.borderWidth = 2.0
        thirdCodeTextField.layer.borderWidth = 2.0
        fourthCodeTextField.layer.borderWidth = 2.0
        
        startTimer()
    }
    
    deinit {
        codeTimer.invalidate()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        firstCodeTextField.becomeFirstResponder()
    }
    

    // MARK: - Private Method
    
    func resetTextFields() {
        self.firstCodeTextField.text = ""
        self.secondCodeTextField.text = ""
        self.thirdCodeTextField.text = ""
        self.fourthCodeTextField.text = ""
    }
    
    func startTimer() {
        if codeTimer != nil {
            codeTimer.invalidate()
        }
        self.codeSeconds = 60
        codeTimer = Timer.init(timeInterval: 1, repeats: true, block: { (timer) in
            if self.codeSeconds == 0 {
                self.secondsLabel.isHidden = true
                self.tipsLabel.isHidden = true
                self.resendButton.isHidden = false
                
                
                self.codeTimer.invalidate()
            }else {
                self.codeSeconds = self.codeSeconds - 1
                self.secondsLabel.text = "\(self.codeSeconds)"
            }
        })
    }
    
    // MARK: - IBAction
    
    @IBAction func resendSMS() {
        startTimer()
        let fetchCode = FetchVerifyCodeRequest(mobile: self.phoneNum!)
        fetchCode.startWithCompletionBlock(success: { (request) in
            let json = JSON(request.responseObject as Any)
            if let code = json["code"].int, code == 0 {
                MBProgressHUD.showTips(tip: "验证码已发送", view: self.view)
            }else {
                MBProgressHUD.showTips(tip: "验证码发送失败", view: self.view)
            }
        }) { (request) in
            
        }
    }

}

extension VerifyCodeViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text, let superView = textField.superview else {
            return true
        }
        
        let nextTag = textField.tag + 1;
        let nextResponder = superView.viewWithTag(nextTag)
        
        if nextResponder == nil {
            let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
            guard let firstLetter = firstCodeTextField.text,
                let secondLetter = secondCodeTextField.text,
                let thirdLetter = thirdCodeTextField.text else {
                return false
            }
            guard let phone = self.phoneNum else {
                return false
            }
            
            let code = "\(firstLetter)\(secondLetter)\(thirdLetter)\(string)"
            print("code  is \(code)")
            let verifyCodeRequest = VerifyCodeRequest(mobile: phone, code: code)
            verifyCodeRequest.startWithCompletionBlock(success: { (request) in
                
                let json = JSON(request.responseObject as Any)
                if let code = json["code"].int, code == 0 {
                    if let token = json["token"].string {
                        UserDefaults.standard.saveAuthenticationToken(token: token)
                    }
                    if let data = json["data"].dictionaryObject {
                        let user = User.yy_model(with: data)
                        print(user?.phoneNumber)
                    }
                    if let appdelegate = UIApplication.shared.delegate as? AppDelegate {
                        appdelegate.LoginSuccess()
                    }
                }else {
                    MBProgressHUD.showTips(tip: "验证码错误", view: self.view)
                    self.resetTextFields()
                    self.firstCodeTextField.becomeFirstResponder()
                }
            }, failure: { (request) in
                MBProgressHUD.showTips(tip: "验证码错误", view: self.view)
            })
            
        }
        nextResponder?.becomeFirstResponder()
        if text.characters.count == 0 {
            textField.text = string
        }
        return false
    }

}

extension VerifyCodeViewController: URLNavigable {
    convenience init?(navigation: Navigation) {
        self.init()
    }
}
